import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:studymanage/core/global.dart';
import 'package:studymanage/course/course.dart';
import 'package:studymanage/message/message.dart';
import 'package:studymanage/mine/mine.dart';
import 'package:studymanage/remark/remark.dart';
import 'package:studymanage/util/jpush_manager.dart';

import 'core/event_bus.dart';
import 'login/login.dart';

class Home extends StatefulWidget {
  final Role role;

  Home(this.role);

  @override
  HomeState createState() => HomeState();
}

// 用户角色
enum Role {teacher, student}

class HomeState extends State<Home> {
  List<Widget> pageList = List<Widget>();
  List<BottomNavigationBarItem> navList = List<BottomNavigationBarItem>();
  int _currentIndex = 0;

  bool loading = true;
  StreamSubscription _responseSubscription;

  StreamSubscription _loadingSubscription;


  @override
  void initState() {
    //设置极光推送别名
    JpushManager.instance.jpush.setAlias(Global.profile.phone);
    JpushManager.instance.jpush.setBadge(0);
    JpushManager.instance.jpush.clearAllNotifications();
    setState(() {
      _loadingSubscription =  eventBus.on<LoadingEvent>().listen((event) {
        if(event.code ==40001){
          _loadingSubscription.cancel();
          return;
        }
        if(mounted) {
          if (event.status && !loading) {
            Future.delayed(Duration(seconds: 2), () {
              setState(() {
                loading = event.status;
              });
            });
          } else {
            setState(() {
              loading = event.status;
            });
          }
        }
      });

      _responseSubscription = eventBus.on<RequestEvent>().listen((messageEvent) {
        if(messageEvent.responseModel.code ==40001){
          _responseSubscription.cancel();
          return;
        }
        if (messageEvent.responseModel.code != 200) {
          Fluttertoast.showToast(
              msg: messageEvent.responseModel.msg,
              toastLength: Toast.LENGTH_LONG,
              gravity: ToastGravity.TOP,
              textColor: Colors.white,
              backgroundColor: Colors.grey,
              fontSize: 12
          );
          if(messageEvent.responseModel.code ==401){
            Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) =>Login(2)), (route) => false);
          }
          //退出登陆
        }
      });
    });

    super.initState();
    switch (widget.role) {
      case Role.teacher:
        navList..add(courseNav())..add(remarkNav())..add(messageNav())..add(mineNav());
        pageList..add(Course())..add(Remark())..add(Message())..add(Mine());
        break;
      case Role.student:
        pageList..add(Course())..add(Message())..add(Mine());
        navList..add(courseNav())..add(messageNav())..add(mineNav());
        break;
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    ScreenUtil.instance = ScreenUtil(width: 375, height: 668, allowFontScaling: true)..init(context);
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Stack(
        children: <Widget>[
          pageList[_currentIndex],
          Positioned(
            bottom: 0,
            child: Container(
              height: 80,
              width: MediaQuery.of(context).size.width,
              child: BottomNavigationBar(
                currentIndex: _currentIndex,
                type: BottomNavigationBarType.fixed,
                backgroundColor: Colors.white,
                iconSize: ScreenUtil().setHeight(21),
                selectedItemColor: Color.fromRGBO(214, 178, 128, 1),
                unselectedItemColor: Color.fromRGBO(142, 142, 142, 1),
                selectedFontSize: ScreenUtil().setSp(10),
                unselectedFontSize: ScreenUtil().setSp(10),
                selectedLabelStyle: TextStyle(
                  fontFamily: 'PingFangSC-Regular',
                  fontWeight: FontWeight.normal,
                ),
                unselectedLabelStyle: TextStyle(
                  fontFamily: 'PingFangSC-Light',
                  fontWeight: FontWeight.w300,
                ),
                items: navList,
                onTap: (int index) {
                  setState(() {
                    _currentIndex = index;
                  });
                },
              ),
            ),
          ),
          Offstage(
              offstage: true,
              child: Container(
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
//                    Image.asset("assets/images/circle_loading.gif")
//                    Loading(indicator: BallSpinFadeLoaderIndicator(),color: Colors.orange,),
                  ],
                ),
              ))
        ],
      ),
    );
  }

  BottomNavigationBarItem courseNav() {
    return BottomNavigationBarItem(
      icon: Image.asset('assets/images/nav_bar/icon_1.png'),
      activeIcon: Image.asset('assets/images/nav_bar/icon_1_selected.png'),
      title: Text('课程'),
    );
  }

  BottomNavigationBarItem remarkNav() {
    return BottomNavigationBarItem(
      icon: Image.asset('assets/images/nav_bar/icon_2.png'),
      activeIcon: Image.asset('assets/images/nav_bar/icon_2_selected.png'),
      title: Text('点评'),
    );
  }

  BottomNavigationBarItem mineNav() {
    return BottomNavigationBarItem(
      icon: Image.asset('assets/images/nav_bar/icon_3.png'),
      activeIcon: Image.asset('assets/images/nav_bar/icon_3_selected.png'),
      title: Text('我的'),
    );
  }

  BottomNavigationBarItem messageNav() {
    return BottomNavigationBarItem(
      icon: Image.asset('assets/images/login/kc_xxjh.png'),
      activeIcon: Image.asset('assets/images/login/kc_xxjhbe.png'),
      title: Text('消息'),
    );
  }
}
